package org.java.pay.conf;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-20 0020 上午 10:09
 * 解决服务与服务之间调用丢失cookie导致token找不到的配置类
 */
@Configuration
@Slf4j
public class FeignHeaderConfig {
    /**
     * 在请求中进行拦截cookie，将cookie放到请求头中
     * @return
     */
    @Bean
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attrs != null) {
                HttpServletRequest request = attrs.getRequest();
                // 如果在Cookie内通过如下方式取
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        requestTemplate.header(cookie.getName(), cookie.getValue());
                        System.out.println("信息"+cookie.getName()+cookie.getValue());
                    }
                } else {
                    log.warn("FeignHeadConfiguration", "获取Cookie失败！");
                }
            }
        };
    }
}
